package com.spzx.payment.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.payment.service.AlipayService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName PaymentReceiver
 * @Author 波
 * @Date 2024/8/16 17:17
 */
@Component
@Slf4j
public class PaymentReceiver {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private RedisTemplate redisTemplate;
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PAYMENT_PAY, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_CLOSE, durable = "true"),
            key = MqConst.ROUTING_PAYMENT_CLOSE
    ))
    public void closePayment(String orderNo, Message message, Channel channel) {
       String lockKey="mq:payment:close:lock"+orderNo;
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, orderNo, 300, TimeUnit.SECONDS);
        if(!flag){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }
        try {
            //业务处理
            if (StringUtils.isNotEmpty(orderNo)) {
                log.info("[支付服务]监听关闭交易消息：{}", orderNo);
                alipayService.closePayment(orderNo);
            }
            //手动应答
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            e.printStackTrace();
        }
    }

}
